package org.listener.socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Create by bo.chen in 2018/9/28 下午5:30
 */
public class Client {

    private final static int PORT = 9000;

    private final static String IP = "localhost";

    private static Socket socket = null;

    static {
        try {
            socket = new Socket(IP, PORT);
        } catch (IOException e) {
            throw new RuntimeException(" Failed to connect " + IP + " " + PORT + ".");
        }
    }

    public void start() throws IOException, InterruptedException {

        System.out.println("connection success");

        PrintWriter out =new PrintWriter(socket.getOutputStream(),true);

        Thread t = new Thread(new Receive(socket));
        t.start();

        //键盘输入
        Scanner scanner =new Scanner(System.in);
        while(scanner.hasNextLine()){
            String input = scanner.nextLine();
            if("\\x0a".equals(input) || "\\cJ".equals(input) || "".equals(input.trim())) {
                continue;
            }
            out.println(input);
        }
    }

    public static void main(String[] args) {
        try {
            new Client().start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Input {
    private Socket socket;
    public Input(Socket socket) {
        this.socket=socket;
    }
    public void in(String message)  throws IOException {
        PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
        out.println(message);
    }
}

class Receive implements Runnable {
    private Socket socket;
    public Receive(Socket socket) {
        this.socket=socket;
    }

    @Override
    public void run() {
        try {
            Scanner scanner =new Scanner(socket.getInputStream());
            Input input = new Input(socket);
            while(true){
                String message = scanner.nextLine();
                System.out.println(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
